package 练习11_线程池综合使用案例;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName: ThreadPoolStudy01
 * @Author: AllenSun
 * @Date: 2025/10/23 23:17
 */
public class ThreadPoolStudy01_execute {
    public static void main(String[] args) {
        UserAccount zhangsan = new UserAccount("张三",9);
        UserAccount lisi = new UserAccount("李四",0);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        double amount = 1;

        for (int i = 0; i < 10; i++) {

            executorService.execute(()->{
                try {
                    transfer01(zhangsan,lisi,amount);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            });

        }

        ThreadPoolShutdownHelper.gracefulShutdown(executorService);

    }

    public static void transfer01(UserAccount from,UserAccount to,double amount) throws InterruptedException {
        synchronized (UserAccount.class) {
            double fromBalance = from.getBalance();
            double toBalance = to.getBalance();
            if (fromBalance >= amount) {
                from.setBalance(fromBalance - amount);
                Thread.sleep(100);
                to.setBalance(toBalance + amount);
                System.out.println("当前线程："+Thread.currentThread().getName()+"；转出账户：" + from.getUserName() + "，余额：" + from.getBalance()+
                        "；转入账户：" + to.getUserName() + "，余额：" + to.getBalance());
            } else {
                System.out.println("当前线程："+Thread.currentThread().getName()+"；余额不足");
                // throw new RuntimeException("余额不足");
                int a=1/0;
            }
        }
    }
}
